import { v4 as uuidv4 } from 'uuid';
import { SchemeInfo, SchemeItem, SchemeItemInfo } from './types';

const SCHEME_KEY = 'SCHEME_INFO';
const PROTABLE_KEY = 'PRO_TABLE_DYNAMIC';
const PROFORM_KEY = 'PRO_FORM_DYNAMIC';

const storage = {
  /**
   * 存储ProTableInfo
   * key 存在 覆盖 不存在 新增
   */
  saveProTableInfo(proTableContexteValueString: string, key?: string) {
    const schemeString: string | null = localStorage.getItem(SCHEME_KEY);
    let schemeInfo: SchemeInfo = schemeString
      ? JSON.parse(schemeString)
      : {
          proTableDynamic: {
            schemeList: [],
          },
          proFormDynamic: {
            schemeList: [],
          },
        };
    if (key) {
      schemeInfo.proTableDynamic.schemeList = schemeInfo.proTableDynamic.schemeList.map((item: SchemeItem) => {
        if (item.key === key) {
          return {
            key: item.key,
            title: item.title,
            data: proTableContexteValueString,
          };
        } else {
          return item;
        }
      });
    } else {
      schemeInfo.proTableDynamic.schemeList.push({
        key: uuidv4(),
        title: uuidv4(),
        data: proTableContexteValueString,
      });
    }
    localStorage.setItem(SCHEME_KEY, JSON.stringify(schemeInfo));
  },
  /**
   * 删除ProTableInfo
   */
  removeProTableInfo(key: string) {
    const schemeString: string | null = localStorage.getItem(SCHEME_KEY);
    if (!schemeString) return;
    let schemeInfo: SchemeInfo = JSON.parse(schemeString);

    schemeInfo.proTableDynamic.schemeList = schemeInfo.proTableDynamic.schemeList.filter((item: SchemeItem) => {
      return item.key !== key;
    });

    localStorage.setItem(SCHEME_KEY, JSON.stringify(schemeInfo));
  },

  /**
   * 获取缓存
   */
  getProTableInfo() {
    const schemeString: string | null = localStorage.getItem(SCHEME_KEY);
    let schemeInfo: SchemeInfo = schemeString
      ? JSON.parse(schemeString)
      : {
          proTableDynamic: {
            schemeList: [],
          },
          proFormDynamic: {
            schemeList: [],
          },
        };
    return schemeInfo.proTableDynamic;
  },
};

export default storage;
